package com.jrx.anytxn.param.job.bactchBillCompare.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.FileUtils;
import com.jrx.anytxn.param.config.BillCompareConfig;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.job.bactchBillCompare.bean.WexinFileNameBean;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 收单系统-微信还款对账文件检查定义
 *
 * @author : chenjin
 * 2022/11/28
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class WexinBillFileCheckConfig {

    private static final Logger logger = LoggerFactory.getLogger(WexinBillFileCheckConfig.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    private BillCompareConfig billCompareConfig;

    @Bean
    public Job wexinBillFileCheckJob() {
        return jobBuilderFactory.get("wexinBillFileCheckJob")
                .start(wexinBillFileCheckStep())
                .build();
    }

    @Bean
    public Step wexinBillFileCheckStep() {
        return stepBuilderFactory.get("wexinBillFileCheckStep").tasklet(wexinBillFileCheckTasklet()).build();
    }

    @Bean
    public Tasklet wexinBillFileCheckTasklet() {
        return (step, context) -> {
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.XIB_ORG_NUMBER);
            // 设置指定对账日期
            Date today = billCompareConfig.getToday();
            if (Objects.nonNull(today)) {
                org.setToday(today);
            }

            // 参与目录路径计算的日期，yyyyMMdd
            String fileDate = DateUtils.format(org.getToday(), DateUtils.DATE_PATTERN_ANOTHER);

            // 系统业务日期，yyyy-MM-dd
            String businessDate = DateUtils.format(org.getToday());

            // 对账文件三方渠道号，由批次任务链参数传入
            String thirdChannel = billCompareConfig.getThirdChannel();

            // 指定日期的对账文件所在目录
            String path = WexinFileNameBean.directory(billCompareConfig.getFilePath(), thirdChannel, fileDate);
            logger.info("微信还款对账文件检查开始，渠道号:{} 业务日期为:{} 路径为:{} ", thirdChannel, businessDate, path);

            int i = 1;
            while (i <= billCompareConfig.getReadCount()) {
                List<WexinFileNameBean> beans = FileUtils.findFiles(path).stream()
                        .map(File::getName)
                        .map(WexinFileNameBean::extract)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                if (beans.size() > 0) {
                    logger.info("微信还款对账文件验证通过，业务日期为:{} ", businessDate);
                    return RepeatStatus.FINISHED;
                } else {
                    Thread.sleep(billCompareConfig.getReadPeriod());
                    i++;
                }
            }

            if (i > billCompareConfig.getReadCount()) {
                logger.error("文件循环检查已超过{}次，检查作业将停止，业务日期为:{}", billCompareConfig.getReadCount(), businessDate);
            }

            return RepeatStatus.FINISHED;
        };
    }
}